<template>
  <view class="container">
    <view class="logo-section">
      <image class="logo" src="/static/logo.png" mode="aspectFit" />
      <text class="app-name">家电商城</text>
    </view>

    <!-- <view class="form-section">
      <uni-forms ref="form" :model="formData" :rules="rules">
        <uni-forms-item name="username">
          <uni-easyinput
            v-model="formData.username"
            placeholder="请输入用户名"
            :clearable="true"
            :prefixIcon="'person'"
          />
        </uni-forms-item>

        <uni-forms-item name="password">
          <uni-easyinput
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            :clearable="true"
            :prefixIcon="'locked'"
          />
        </uni-forms-item>
      </uni-forms>

      <button class="login-btn" @click="login">登录</button>
    </view> -->

    <!-- 手机号快捷登录 -->
    <view class="wechat-login-section">
      <!-- 简化的微信登录按钮 -->
      <button
        class="wechat-login-btn"
        open-type="getUserInfo"
        @getuserinfo="getuserinfo"
        withCredentials="true"
        :disabled="wechatLogging"
      >
        <image class="wechat-icon" src="/static/icons/wechat.png" mode="aspectFit" />
        <text class="wechat-text">{{ wechatLogging ? '登录中...' : '手机号快捷登录' }}</text>
      </button>
      <button
        class="wechat-login-btn"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber"
        withCredentials="true"
        :disabled="wechatLogging"
      >
        <text class="wechat-text">获取手机号</text>
      </button>
    </view>

    <!-- 快速登录（仅用于测试） -->
    <view class="quick-login">
      <text class="quick-title">快速登录（测试用）</text>
      <view class="quick-buttons">
        <button class="quick-btn normal" @click="quickLogin('normal')">普通用户</button>
        <button class="quick-btn sales" @click="quickLogin('sales')">销售人员</button>
      </view>
    </view>

    <!-- 注册链接 -->
    <!-- <view class="register-link">
      <text>还没有账号？</text>
      <text class="link" @click="goToRegister">立即注册</text>
    </view> -->

    <!-- 用户协议 -->
    <view class="agreement">
      <text>登录即表示同意</text>
      <text class="link">《用户协议》</text>
      <text>和</text>
      <text class="link">《隐私政策》</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onUnload } from '@dcloudio/uni-app';

const form = ref();
const wechatLogging = ref(false);
const referralCode = ref('');

// 表单数据
const formData = reactive({
  username: '',
  password: '',
});

// 表单验证规则
const rules = {
  username: {
    rules: [
      { required: true, errorMessage: '请输入用户名' },
      {
        minLength: 3,
        maxLength: 20,
        errorMessage: '用户名长度在3-20个字符之间',
      },
    ],
  },
  password: {
    rules: [
      { required: true, errorMessage: '请输入密码' },
      { minLength: 6, maxLength: 20, errorMessage: '密码长度在6-20个字符之间' },
    ],
  },
};

// 微信获取用户信息并打印
const getuserinfo = () => {
  uni.login({
    success: (res: any) => {
      if (res.code) {
        console.log('成功', res);

        //获取token
        uni.request({
          url: 'https://api.weixin.qq.com/cgi-bin/token',
          success: (res_token: any) => {
            console.log(res_token);
          },
        });

        // 获取手机号
        // https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN

        // uni.request({
        //   url: 'https://api.weixin.qq.com/sns/jscode2session',
        //   data: {
        //     appid: 'wx3857e85d91d69098',
        //     secret: '84d063cc22d3b7cbda2f258960726b97',
        //     js_code: res.code,
        //     grant_type: 'authorization_code',
        //   },
        //   success: (res: any) => {
        //     console.log(res);
        //   },
        // });
      }
      // 这里可以将code发送到后端获取openid和session_key
    },
    fail: (err: any) => {
      console.log('登录失败:', err);
    },
  });
};

// 获取手机号
const getPhoneNumber = (e: any) => {
  if (e.detail.code) {
    uni.login({
      success: async (res: any) => {
        if (res.code) {
          const requestData: any = {
            clientId: 'be7052a7e4f802c20df10a8d131adb12',
            grantType: 'xcx',
            code: res.code,
            iv: e.detail.iv,
            encryptedData: e.detail.encryptedData,
          };

          // 如果有推广码（用户ID），添加到请求数据中
          if (referralCode.value) {
            requestData.referralCode = referralCode.value;
            console.log('包含推广码（用户ID）:', referralCode.value);
          } else {
            console.log('无推广码，直接获取手机号');
          }

          // 调用接口，模拟登录请求
          uni.showLoading({
            title: '登录中...',
          });

          try {
            // const a = await xx()
            uni.showToast({
              title: '登录成功',
              icon: 'success',
            });

            // 保存用户信息
            uni.setStorageSync('userInfo', {
              id: 1,
              username: formData.username,
              nickname: formData.username,
              userType: 'normal', // normal: 普通用户, sales: 销售人员
              phone: '',
              avatar: '/static/avatar.png',
            });

            // 跳转到个人中心
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/user/profile',
              });
            }, 1500);
            uni.hideLoading();
          } catch (error) {
            uni.showToast({
              title: '登录失败',
              icon: 'none',
            });
            uni.hideLoading();
          }

          // getAccessToken(e.detail.code);
        }
      },
    });
    // 获取到手机号code，调用getAccessToken方法
  } else {
    uni.showToast({
      title: '获取手机号失败',
      icon: 'none',
    });
  }
};

// 获取access_token并调用微信获取手机号接口
const getAccessToken = (phoneCode: string) => {
  const appid = 'wx932d383755e54e77';
  const secret = '9c5746a277da6341e837b826e52de3d7';
  // 第一步：获取access_token
  uni.request({
    url: 'https://api.weixin.qq.com/cgi-bin/token',
    data: {
      grant_type: 'client_credential',
      appid: appid,
      secret: secret,
    },
    method: 'GET',
    success: (res: any) => {
      console.log('获取access_token结果:', res);

      if (res.data && res.data.access_token) {
        // 第二步：使用access_token和phoneCode获取手机号
        getPhoneNumberFromWechat(res.data.access_token, phoneCode);
      } else {
        console.error('获取access_token失败:', res.data);
        uni.showToast({
          title: '获取access_token失败',
          icon: 'none',
        });
      }
    },
    fail: (err: any) => {
      console.error('请求access_token失败:', err);
      uni.showToast({
        title: '网络请求失败',
        icon: 'none',
      });
    },
  });
};

// 调用微信获取手机号接口
const getPhoneNumberFromWechat = (accessToken: string, phoneCode: string) => {
  // 构建请求数据，如果有推广码则包含
  const requestData: any = {
    code: phoneCode,
  };

  // 如果有推广码（用户ID），添加到请求数据中
  if (referralCode.value) {
    requestData.referralCode = referralCode.value;
    console.log('包含推广码（用户ID）:', referralCode.value);
  } else {
    console.log('无推广码，直接获取手机号');
  }

  uni.request({
    url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`,
    data: requestData,
    method: 'POST',
    header: {
      'content-type': 'application/json',
    },
    success: (res: any) => {
      console.log('获取手机号结果:', res);

      if (res.data && res.data.errcode === 0) {
        const phoneInfo = res.data.phone_info;
        console.log('手机号信息:', phoneInfo);

        // 如果有推广码，显示推广信息
        const successMessage = referralCode.value
          ? `获取成功: ${phoneInfo.phoneNumber} (推广邀请已记录)`
          : `获取成功: ${phoneInfo.phoneNumber}`;

        uni.showToast({
          title: successMessage,
          icon: 'success',
        });

        // 这里可以保存手机号信息或进行后续登录操作
        // 例如：保存到本地存储或发送到后端，包含推广码信息
        const loginData = {
          phone: phoneInfo.phoneNumber,
          referralCode: referralCode.value || null,
          timestamp: new Date().toISOString(),
        };
        console.log('登录数据（包含推广信息）:', loginData);

        // 模拟保存用户信息并包含推广关系
        const userInfo = {
          id: Date.now(), // 模拟用户ID
          username: phoneInfo.phoneNumber,
          nickname: phoneInfo.phoneNumber,
          avatar: '/static/avatar.png',
          userType: 'normal',
          phone: phoneInfo.phoneNumber,
          referredBy: referralCode.value || null, // 推荐人ID
        };

        uni.setStorageSync('userInfo', userInfo);
        console.log('用户信息已保存:', userInfo);
      } else {
        console.error('获取手机号失败:', res.data);
        uni.showToast({
          title: '获取手机号失败',
          icon: 'none',
        });
      }
    },
    fail: (err: any) => {
      console.error('请求手机号失败:', err);
      uni.showToast({
        title: '网络请求失败',
        icon: 'none',
      });
    },
  });
};

// 登录
const login = () => {
  form.value?.validate().then((res: any) => {
    if (res.valid) {
      // 模拟登录请求
      uni.showLoading({
        title: '登录中...',
      });

      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '登录成功',
          icon: 'success',
        });

        // 保存用户信息
        uni.setStorageSync('userInfo', {
          id: 1,
          username: formData.username,
          nickname: formData.username,
          userType: 'normal', // normal: 普通用户, sales: 销售人员
          phone: '',
          avatar: '/static/avatar.png',
        });

        // 跳转到个人中心
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/user/profile',
          });
        }, 1500);
      }, 2000);
    }
  });
};

// 快速登录（测试用）
const quickLogin = (userType: string) => {
  uni.showLoading({
    title: '登录中...',
  });

  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    });

    // 保存用户信息
    const userInfo = {
      id: 1,
      username: userType === 'sales' ? 'sales001' : 'user001',
      nickname: userType === 'sales' ? '销售人员' : '普通用户',
      avatar: '/static/avatar.png',
      userType: userType,
      phone: '',
    };

    uni.setStorageSync('userInfo', userInfo);

    // 跳转到个人中心
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/user/profile',
      });
    }, 1500);
  }, 1000);
};

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/user/register',
  });
};

// 页面加载时检查推广码
onMounted(() => {
  // 获取页面参数中的推广码
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;

  // 检查直接传入的referralCode参数
  if (options && options.referralCode) {
    referralCode.value = options.referralCode;
    console.log('检测到直接传入的推广码:', referralCode.value);
    uni.showToast({
      title: '检测到推广邀请',
      icon: 'success',
    });
  }
  // 检查scene参数（扫码进入）
  else if (options && options.scene) {
    // 解析scene参数，格式为 referral=userId
    const sceneParams = decodeURIComponent(options.scene);
    const referralMatch = sceneParams.match(/referral=(\d+)/);
    if (referralMatch) {
      referralCode.value = referralMatch[1];
      console.log('检测到扫码推广码:', referralCode.value);
      uni.showToast({
        title: '检测到推广邀请',
        icon: 'success',
      });
    }
  }

  console.log('当前推广码状态:', referralCode.value || '无');
});

// 页面卸载时清空推广码
onUnload(() => {
  referralCode.value = '';
  console.log('页面离开，推广码已清空');
});
</script>

<style scoped>
.container {
  padding: 60rpx 40rpx;
  background-color: #fff;
  min-height: 100vh;
}

.logo-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
}

.app-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-section {
  margin-bottom: 40rpx;
}

.login-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 40rpx;
}

/* 微信登录样式 */
.wechat-login-section {
  margin: 40rpx 0;
  text-align: center;
}

.wechat-login-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #1aad19;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.wechat-icon {
  width: 40rpx;
  height: 40rpx;
}

.wechat-text {
  font-size: 32rpx;
}

.quick-login {
  margin-bottom: 40rpx;
  padding: 30rpx;
  background-color: #f8f9fa;
  border-radius: 20rpx;
}

.quick-title {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  display: block;
  margin-bottom: 20rpx;
}

.quick-buttons {
  display: flex;
  gap: 20rpx;
}

.quick-btn {
  flex: 1;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 24rpx;
  border-radius: 30rpx;
  border: none;
}

.quick-btn.normal {
  background-color: #28a745;
  color: #fff;
}

.quick-btn.sales {
  background-color: #ff6b35;
  color: #fff;
}

.register-link {
  text-align: center;
  margin-bottom: 40rpx;
  font-size: 28rpx;
  color: #666;
}

.link {
  color: #007aff;
  margin-left: 10rpx;
}

.agreement {
  text-align: center;
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
}

.agreement .link {
  color: #007aff;
}
</style>
